package com.palmcity.rtti.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.palmcity.rtti.base.DTIJam.DTIJamComparator;



/**
 * <p>DTIMesh</p>
 * <p>DTI网格实体</p>
 *
 * @author		周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version		0.0.0
 * <table style="border:1px solid gray;">
 * <tr>
 * <th width="100px">版本号</th><th width="100px">动作</th><th width="100px">修改人</th><th width="100px">修改时间</th>
 * </tr>
 * <!-- 以 Table 方式书写修改历史 -->
 * <tr>
 * <td>0.0.0</td><td>创建类</td><td>zhouhuabin</td><td>2014年12月30日 下午3:50:57</td>
 * </tr>
 * <tr>
 * <td>XXX</td><td>XXX</td><td>XXX</td><td>XXX</td>
 * </tr>
 * </table>
*/
public class DTIMesh implements Serializable {

	/** TODO */
	private static final long serialVersionUID = -5783809168138525522L;
	
	/** 网格编号 */
	private int meshId;
	/** 路链对象列表 */
	private final List<IDTI> dtiList=new LinkedList<IDTI>();;

	/**
	 * 构造器 
	 */
	public DTIMesh() {
		meshId = -1;
	}

	
	/**
	 * 字段 meshId 获取函数
	 * @return the meshId : int
	 */
	public int getMeshId() {
		return meshId;
	}


	/**
	 * 字段 meshId 设置函数 : int
	 * @param meshId the meshId to set
	 */
	public void setMeshId(int meshId) {
		this.meshId = meshId;
	}


	/**
	 * FIXME 
	 * @return
	 */
	public List<IDTI> getDtiList() {
		return dtiList;
	}

	/**
	 * add IDTI into DTIMesh
	 * 
	 * @param dti
	 *            DTIJam or DTIEvent or DTIParking
	 */
	public void addDTI(IDTI dti) {
			dtiList.add(dti);
	}

	/**
	 * when IDIT is DTIJam instance,sort asc by linkid
	 */
	public void sort() {
		if (!isDtiEmpty()) {
			if (this.dtiList.get(0) instanceof DTIJam) {
				Map<Integer, List<IDTI>> meshes = new HashMap<Integer, List<IDTI>>();
				for (int i = 0; i < this.dtiList.size(); i++) {
					int rc = ((DTIJam) this.dtiList.get(i)).getLink()
							.getRoadClass();
					if (meshes.containsKey(rc)) {
						meshes.get(rc).add(this.dtiList.get(i));
					} else {
						meshes.put(rc, new ArrayList<IDTI>());
						meshes.get(rc).add(this.dtiList.get(i));
					}
				}
				this.dtiList.clear();
				for (Iterator<List<IDTI>> ii = meshes.values().iterator(); ii
						.hasNext();) {
					List<IDTI> result = ii.next();
					Collections.sort(result, new DTIJamComparator());
					this.dtiList.addAll(result);
				}
				meshes = null;
			} else if (this.dtiList.get(0) instanceof DTIEvent) {
				for (int it = 0; it < this.dtiList.size(); it++) {
					DTIEvent eventSin = (DTIEvent) this.dtiList.get(it);
					if((eventSin.getEventLocation().getAffectLinks() - 2) > 1){
						eventSin.getEventLocation().sort();
					}
				}
			}
		}
	}

	/**
	 * check data is null
	 * 
	 * @return true or false
	 */
	public boolean isDtiEmpty() {
		return dtiList.isEmpty();
	}

}